package com.kkb.interceptor;

import com.kkb.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Lxy
 * @create 2022-03-19 12:23
 */

public class LoginInterceptor implements HandlerInterceptor {

    //登录拦截器拦截除登录页面以外所有页面访问请求
    //表示在ModelAndView方法执行前先执行，可以处理登录拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User)request.getSession().getAttribute("user");
        if (user != null){
            //表示不拦截
            System.out.println("不拦截");
            return true;
        }
        //拦截并且返回登录页面
        System.out.println("拦截");
        response.sendRedirect(request.getContextPath() + "/welcome/login.html");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
